package com.dongdongshop.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //shiro的过滤器
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        //设置安全管理
        factoryBean.setSecurityManager(securityManager);
        //定义过滤器
        Map<String,String> map = new LinkedHashMap<>(); //LinkedHashMap表示有序的map
        //选放过,再拦截,key是路径 value就是shiro的过滤器
        //放过静态资源
        map.put("/css/**","anon");
        map.put("/img/**","anon");
        map.put("/js/**","anon");
        map.put("/plugins/**","anon");
        //登陆页面加载
        map.put("/shoplogin/zhuce","anon");
        map.put("/shoplogin/denglu","anon");
        map.put("/shoplogin/toshoplogin","anon");
        map.put("/shoplogin/toregistee","anon");
        map.put("/**","authc");
        //设置登录网页
        factoryBean.setLoginUrl("/shoplogin/toshoplogin");

        //需要将map放到过滤器工厂类中
        factoryBean.setFilterChainDefinitionMap(map);
        return factoryBean;
    }

    //实例化安全管理类
    @Bean
    public DefaultWebSecurityManager securityManager(@Autowired LoginRealm loginRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //设置realm
        securityManager.setRealm(loginRealm);
        return securityManager;
    }

    //实例化自定义的realm类
    @Bean
    public LoginRealm loginRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        LoginRealm realm = new LoginRealm();
        realm.setCredentialsMatcher(hashedCredentialsMatcher);
        return realm;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        //加密工具类
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //加密算法的名字
        credentialsMatcher.setHashAlgorithmName("MD5");
        //2加密次数
        credentialsMatcher.setHashIterations(3);
        //3设置编码
        credentialsMatcher.setStoredCredentialsHexEncoded(true);
        return credentialsMatcher;
    }
}
